package com.android.mios;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.android.mios.adapter.BottomNavigationGridViewAdapter;
import com.android.mios.adapter.RoomPopGridViewAdapter;
import com.android.mios.adapter.ScenePopGridViewAdapter;
import com.android.mios.db.MainDBAdapter;
import com.android.mios.intenet.PollLoop;
import com.android.mios.intenet.WebData;
import com.android.mios.listener.RoomChangedListener;
import com.android.mios.model.Engine;
import com.android.mios.model.Room;
import com.android.mios.model.Scene;
import com.android.mios.util.Constants;
import com.android.mios.util.Global;
import com.android.mios.util.PathAnimItem;
import com.android.mios.util.PathAnimMenu;
import com.android.mios.util.PathAnimMenuLinster;
import com.android.mios.util.Settings;
import com.android.mios.util.TLog;
import com.android.mios.weather.GetWeatherInfo;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivityGroup extends AbstractMyActivityGroup implements
		OnClickListener, OnLongClickListener {

	// 加载的Activity的名字，LocalActivityManager就是通过这些名字来查找对应的Activity的。
	private static final String ALL_DEVICE_ACTIVITY = "AllDeviceControlActivity";
	private static final String SCENE_CONTROL_ACTIVITY = "SceneControlActivity";
	private static final String CURTAIN_CONTROL_ACTIVITY = "CurtainControlActivity";
	private static final String LIGHT_CONTROL_ACTIVITY = "LightControlActivity";
	private static final String CAMERA_CONTROL_ACTIVITY = "CameraControlActivity";
	private static final String CLIMATE_LOGIN_ACTIVITY = "ClimateControlActivity";
	private static final String LOCK_CONTROL_ACTIVITY = "LockControlActivity";
	private static final String SENSORS_CONTROL_ACTIVITY = "SensorsControlActivity";
	private static final String SYSTEM_SETTING_ACTIVITY = "SystemSettinglActivity";

	private static final int TOOLBAR_ITEM_ALLDEVICE = 0;//
	private static final int TOOLBAR_ITEM_SCENE = 1;//
	private static final int TOOLBAR_ITEM_LIGHT = 2;//
	private static final int TOOLBAR_ITEM_CURTAIN = 3;//
	private static final int TOOLBAR_ITEM_CLIMATE = 4;//
	private static final int TOOLBAR_ITEM_LOCK = 5;//
	private static final int TOOLBAR_ITEM_SENSORS = 6;//
	private static final int TOOLBAR_ITEM_CAMERA = 7;//
	private static final int TOOLBAR_ITEM_SETTING = 8;//

	private static final int[] IMAGE = { R.drawable.alldevice_icon,
			R.drawable.scene_icon, R.drawable.light_icon,
			R.drawable.curtain_icon, R.drawable.climate_icon,
			R.drawable.lock_icon, R.drawable.sensor_icon,
			R.drawable.camera_icon, R.drawable.setting_icon };

	private TextView txt_weather_info;
	private ImageView iv_weather;
	private Resources res;
	private ArrayList<HashMap<String, Object>> listOfBottomNavigation;
	private Button btn_default1_sensor_setting, btn_default2_sensor_setting;
	private LinearLayout refresh;
	private ArrayList<Room> roomOfArray;
	private ProgressBar mProgressBar;
	private int iPosition = -1;

	private LinearLayout mainLinear;
	// private FrameLayout popLinear;
	private GridView gv_room_list;// 布局形式
	private GridView gv_room_list_pop;// pop形式
	private RoomPopGridViewAdapter mRoomPopGridViewAdapter;
	private ArrayList<OpenSenceAsyncTask> arrayOfOpenSence;
	private boolean isRunning = false;

	// private long translate_duration_time = 400;
	// private long alpha_duration_time = 600;

	// private int engineState;
	private PathAnimMenu pm;
	private LocationClient mLocationClient;
	private LocationClientOption option;
	private int LOCATION_DELAY_MIN = 5 * 1000;
	private int LOCATION_DELAY_MAX = 60 * 60 * 1000;
	private String current_city;

	private float displayMetrics;

	private int iFlag;
	private SharedPreferences mSharedPreferences;
	private String currentUserBg;
	// =====================phone========================
	private LinearLayout linear_scroll_navigation;
	private GridView gridView;
	private BottomNavigationGridViewAdapter mBottomNavigationGridViewAdapter;
	private Button btn_previous_room;
	private Button btn_next_room;
	private TextView txt_currentRoom_name;
	private LinearLayout container;
	int currentRoomPositionInList = 0;
	private PopupWindow popOfAllRoom;

	private ArrayList<Scene> arrayOfScence;
	private ScenePopGridViewAdapter mScenePopGridViewAdapter;
	private ArrayList<String> arrayOfSelectedData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity_group_layout);
		initData();
		initPathButton();
		initView();
		initListens();
		initPopOfAllRoom();
		initPopOfAllScene();
		if (iFlag == Constants.WELCOME_POSITION) {
			int localOrDistance = mSharedPreferences.getInt(
					Constants.LOCAL_OR_DISTANCE, 1);// 0是本地，1是远程
			if (localOrDistance == 1) {
				new GetFetchDataAsyncTask().execute();
			} else {
				PollLoop.getInstance().startPollLoop();
			}
		}

		setContainerView(ALL_DEVICE_ACTIVITY, AllDeviceActivity.class);
	}

	private void initData() {

		res = this.getResources();
		mSharedPreferences = Settings.getInstance().getSharedPreferences();

		currentUserBg = mSharedPreferences.getString(Constants.CURRENT_USER_BG,
				Constants.DEFAULT_USER_BG_1);

		iFlag = getIntent().getIntExtra(Constants.FLAG, 0);

		displayMetrics = Global.getInstance().getDisplayMetrics().density;

		mLocationClient = new LocationClient(this);
		option = new LocationClientOption();
		option.setOpenGps(true); // 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型为bd09ll
		option.setPriority(LocationClientOption.NetWorkFirst); // 设置网络优先
		option.setProdName("locSDKDemo2"); // 设置产品线名称
		option.setScanSpan(LOCATION_DELAY_MIN); // 定时定位，每隔60秒钟定位一次。
		mLocationClient.setLocOption(option);
		mLocationClient.registerLocationListener(new BDLocationListener() {

			@Override
			public void onReceiveLocation(BDLocation location) {
				// TODO Auto-generated method stub

				current_city = location.getCity();
				if (current_city == null) {

					option.setScanSpan(LOCATION_DELAY_MIN);
					mLocationClient.setLocOption(option);

					iv_weather.setVisibility(View.GONE);
					txt_weather_info.setText(Global.getInstance().getMyTitle());

				} else {

					option.setScanSpan(LOCATION_DELAY_MAX);
					mLocationClient.setLocOption(option);

					if (Global.getInstance().getIsRuningWeather() == false)
						new GetWeatherInfo(MainActivityGroup.this,
								current_city, mProgressBar, iv_weather,
								txt_weather_info).execute();

				}

			}

			@Override
			public void onReceivePoi(BDLocation arg0) {
				// TODO Auto-generated method stub

			}
		});

		roomOfArray = new ArrayList<Room>();
		mRoomPopGridViewAdapter = new RoomPopGridViewAdapter(this, roomOfArray,
				R.layout.room_item);

		listOfBottomNavigation = getBottomNavigationData();
		mBottomNavigationGridViewAdapter = new BottomNavigationGridViewAdapter(
				this, listOfBottomNavigation,
				R.layout.gv_bottom_navigation_item);

		arrayOfOpenSence = new ArrayList<OpenSenceAsyncTask>();

		arrayOfSelectedData = new ArrayList<String>();// 根据位置删选后数据
		arrayOfScence = new ArrayList<Scene>();
		mScenePopGridViewAdapter = new ScenePopGridViewAdapter(this,
				arrayOfScence, R.layout.scene_shortcuts_item,
				arrayOfSelectedData);

	}

	boolean sign = false;
	private PopupWindow popOfAllScene;
	private GridView gv_scene_list;
	static final int anicatinoTime = 100;

	@Override
	protected void onResume() {
		super.onResume();
		updateRooms();
		PollLoop.getInstance().addRoomChangedListener(roomChangedListener);
		if (!mLocationClient.isStarted())
			mLocationClient.start();

	}

	private void initPopOfAllRoom() {
		// if (popOfAllRoom == null) {
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.pop_allroom_layout, null);
		popOfAllRoom = new PopupWindow(view, LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT, true);
		popOfAllRoom.setBackgroundDrawable(new BitmapDrawable());

		gv_room_list_pop = (GridView) view.findViewById(R.id.gv_Room_List_pop);

		gv_room_list_pop.setColumnWidth((int) (70 * displayMetrics));
		gv_room_list_pop.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gv_room_list_pop.setAdapter(mRoomPopGridViewAdapter);
		gv_room_list_pop.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				currentRoomPositionInList = position;
				listenBtnState();
				Room mRoom = roomOfArray.get(position);
				Global.getInstance().setRoomID(mRoom.id);
				Global.getInstance().setSerialNumber(mRoom.serialNumber);
				PollLoop.getInstance().refreshAll();
				txt_currentRoom_name.setText(mRoom.name);
				popOfAllRoom.dismiss();
			}
		});
	}

	private void initPopOfAllScene() {
		// if (popOfAllRoom == null) {
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.pop_allroom_layout, null);
		popOfAllScene = new PopupWindow(view, LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT, true);
		popOfAllScene.setBackgroundDrawable(new BitmapDrawable());

		gv_scene_list = (GridView) view.findViewById(R.id.gv_Room_List_pop);

		gv_scene_list.setColumnWidth((int) (70 * displayMetrics));
		gv_scene_list.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gv_scene_list.setAdapter(mScenePopGridViewAdapter);
	}

	private void initPathButton() {
		// ///---------------
		pm = (PathAnimMenu) findViewById(R.id.pm);
		List<PathAnimItem> otherAnimItemList = initOtherAnimItemList();

		// add按钮
		PathAnimItem addItem = new PathAnimItem(this, null);
		addItem.setBackgroundResource(R.drawable.friends_delete);
		pm.addAllItems(otherAnimItemList, addItem);
		pm.setPathAnimMenuLinster(new PathAnimMenuLinster() {

			@Override
			public void didSelectedItem(PathAnimItem item, int index) {
				if (index == 0) {

					Intent intent = new Intent(MainActivityGroup.this,
							LoginUserActivity.class);
					intent.putExtra(Constants.FLAG,
							Constants.MAINGROUP_POSITION);
					MainActivityGroup.this.startActivity(intent);
					finish();
				} else if (index == 1) {

					Intent intent = new Intent(MainActivityGroup.this,
							LoginUserActivity.class);
					intent.putExtra(Constants.FLAG,
							Constants.MAINGROUP_POSITION);
					MainActivityGroup.this.startActivity(intent);
					finish();
				} else if (index == 2) {

					Intent intent = new Intent(MainActivityGroup.this,
							LoginUserActivity.class);
					intent.putExtra(Constants.FLAG,
							Constants.MAINGROUP_POSITION);
					MainActivityGroup.this.startActivity(intent);
					finish();
				}
				overridePendingTransition(R.anim.slide_up_in,
						R.anim.slide_down_out);
			}
		});
	}

	private List<PathAnimItem> initOtherAnimItemList() {
		List<PathAnimItem> resultList = new ArrayList<PathAnimItem>();

		PathAnimItem otherItem = new PathAnimItem(this, null);
		otherItem.setBackgroundResource(R.drawable.composer_camera);
		resultList.add(otherItem);

		otherItem = new PathAnimItem(this, null);
		otherItem.setBackgroundResource(R.drawable.composer_music);
		resultList.add(otherItem);

		otherItem = new PathAnimItem(this, null);
		otherItem.setBackgroundResource(R.drawable.composer_sleep);
		resultList.add(otherItem);

		return resultList;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (mLocationClient.isStarted())
			mLocationClient.stop();

	}

	private RoomChangedListener roomChangedListener = new RoomChangedListener() {
		private Runnable updateUiAction = new Runnable() {
			public void run() {
				updateRooms();
			}
		};

		@Override
		public void roomChanged() {
			runOnUiThread(updateUiAction);

		}
	};

	private void updateRooms() {
		roomOfArray.clear();
		roomOfArray.addAll(getRooms());
		listenBtnState();

	}

	private ArrayList<HashMap<String, Object>> getBottomNavigationData() {

		ArrayList<HashMap<String, Object>> mList = new ArrayList<HashMap<String, Object>>();

		String[] arrayOfTitle = res
				.getStringArray(R.array.lefe_navigation_title);
		String[] arrayOfDescription = res
				.getStringArray(R.array.lefe_navigation_description);

		for (int i = 0; i < arrayOfDescription.length; i++) {

			HashMap<String, Object> map = new HashMap<String, Object>();

			map.put(BottomNavigationGridViewAdapter.TEXT_TITLE, arrayOfTitle[i]);
			map.put(BottomNavigationGridViewAdapter.IMAGE, IMAGE[i]);

			mList.add(map);
		}
		return mList;
	}

	/*
	 * 得到房间信息
	 */
	private ArrayList<Room> getRooms() {

		Map<String, Room> rooms = PollLoop.getInstance().getRooms();
		ArrayList<Room> mRooms = new ArrayList<Room>();
		Room allRoom = new Room();
		allRoom.name = "所有房间";
		allRoom.id = -1;
		allRoom.serialNumber = -1;
		mRooms.add(allRoom);
		mRooms.addAll(rooms.values());
		return mRooms;

	}

	private void initView() {

		btn_default1_sensor_setting = (Button) findViewById(R.id.btn_default1_sensor_setting);
		btn_default1_sensor_setting.setTag(0);
		btn_default2_sensor_setting = (Button) findViewById(R.id.btn_default2_sensor_setting);
		btn_default2_sensor_setting.setTag(1);
		btn_previous_room = (Button) findViewById(R.id.btn_previous_room);
		btn_next_room = (Button) findViewById(R.id.btn_next_room);
		txt_currentRoom_name = (TextView) findViewById(R.id.txt_current_room);
		txt_currentRoom_name.setText(getString(R.string.all_room));
		mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
		iv_weather = (ImageView) findViewById(R.id.iv_weather);// 天气图片
		txt_weather_info = (TextView) findViewById(R.id.txt_weather_info);// 天气提示
		refresh = (LinearLayout) findViewById(R.id.refresh);
		// popLinear = (FrameLayout) findViewById(R.id.popLinear);

		gv_room_list = (GridView) findViewById(R.id.gv_Room_List);
		gv_room_list.setColumnWidth((int) (100 * displayMetrics));
		gv_room_list.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gv_room_list.setAdapter(mRoomPopGridViewAdapter);
		gv_room_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				currentRoomPositionInList = position;
				listenBtnState();
				Room mRoom = roomOfArray.get(position);
				Global.getInstance().setRoomID(mRoom.id);
				Global.getInstance().setSerialNumber(mRoom.serialNumber);
				PollLoop.getInstance().refreshAll();
				txt_currentRoom_name.setText(mRoom.name);

			}
		});

		linear_scroll_navigation = (LinearLayout) findViewById(R.id.linear_scroll_navigation);
		initNavigationGridView();

		container = (LinearLayout) findViewById(R.id.container);

		mainLinear = (LinearLayout) findViewById(R.id.mainLinear);// 背景
		Global.getInstance().setCurrentUserBg(res, currentUserBg, mainLinear);
		Global.getInstance().setMainLayout(mainLinear);
	}

	private void initNavigationGridView() {
		int width = Global.getInstance().getDisplayMetrics().widthPixels / 5;
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width
				* listOfBottomNavigation.size(), (int) (60 * displayMetrics));
		gridView = new GridView(this);
		gridView.setColumnWidth(width);
		gridView.setGravity(Gravity.CENTER);
		gridView.setScrollBarStyle(0);
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gridView.setNumColumns(GridView.AUTO_FIT);
		gridView.setLayoutParams(lp);
		linear_scroll_navigation.addView(gridView);
		gridView.setAdapter(mBottomNavigationGridViewAdapter);
		gridView.setOnItemClickListener(this);
		gridView.setOnTouchListener(new OnTouchListener() {// 禁止垂直滚动

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				return MotionEvent.ACTION_MOVE == event.getAction() ? true
						: false;
			}
		});
		listenBtnState();
	}

	private void initListens() {
		btn_default1_sensor_setting.setOnClickListener(this);
		btn_default2_sensor_setting.setOnClickListener(this);
		btn_default1_sensor_setting.setOnLongClickListener(this);
		btn_default2_sensor_setting.setOnLongClickListener(this);
		btn_previous_room.setOnClickListener(this);
		btn_next_room.setOnClickListener(this);
		txt_currentRoom_name.setOnClickListener(this);
		refresh.setOnClickListener(this);
	}

	private void loadRoomView() {

		LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) gv_room_list_pop
				.getLayoutParams();

		int count = roomOfArray.size();

		lp.width = (int) (count * 70 * displayMetrics)
				+ (int) (((count > 0 ? count : 1) - 1) * 10 * displayMetrics);

		gv_room_list_pop.setNumColumns(roomOfArray.size());
		mRoomPopGridViewAdapter.notifyDataSetChanged();
	}

	// private void showPopWindowScene() {
	//
	// container.setLayoutParams(new LinearLayout.LayoutParams(
	// LinearLayout.LayoutParams.FILL_PARENT, container.getHeight()));
	//
	// popLinear.setVisibility(View.VISIBLE);
	// // popOfAllRoom.showAsDropDown(txt_currentRoom_name, 0,
	// // (int) (15 * displayMetrics));
	//
	// TranslateAnimation pushDown = new TranslateAnimation(0, 0,
	// -(int) ((60 - 10) * displayMetrics), 0);
	// pushDown.setDuration(translate_duration_time);
	// pushDown.setFillAfter(true);
	// container.setAnimation(pushDown);
	//
	// }

	// private void hidePopWindowScene() {
	//
	// TranslateAnimation pushDown = new TranslateAnimation(0, 0,
	// (int) ((60 - 10) * displayMetrics), 0);
	// pushDown.setDuration(translate_duration_time);
	// pushDown.setFillAfter(true);
	// container.setAnimation(pushDown);
	//
	// popLinear.setVisibility(View.GONE);
	// // popOfAllRoom.dismiss();
	//
	// AlphaAnimation alp = new AlphaAnimation(1.0f, 0.0f);
	// alp.setDuration(alpha_duration_time);
	// popLinear.startAnimation(alp);
	// }

	/**
	 * 找到自定义id的加载Activity的View
	 */
	@Override
	protected LinearLayout getContainer() {
		return container;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		mBottomNavigationGridViewAdapter.setSelectItem(position);
		mBottomNavigationGridViewAdapter.notifyDataSetChanged();
		if (position == TOOLBAR_ITEM_ALLDEVICE) {
			if (iPosition != TOOLBAR_ITEM_ALLDEVICE) {
				setContainerView(ALL_DEVICE_ACTIVITY, AllDeviceActivity.class);
				iPosition = TOOLBAR_ITEM_ALLDEVICE;
			}

		} else if (position == TOOLBAR_ITEM_SCENE) {
			if (iPosition != TOOLBAR_ITEM_SCENE) {
				setContainerView(SCENE_CONTROL_ACTIVITY,
						SceneControlActivity.class);
				iPosition = TOOLBAR_ITEM_SCENE;
			}

		} else if (position == TOOLBAR_ITEM_LIGHT) {
			if (iPosition != TOOLBAR_ITEM_LIGHT) {
				setContainerView(LIGHT_CONTROL_ACTIVITY,
						LightControlActivity.class);
				iPosition = TOOLBAR_ITEM_LIGHT;
			}

		} else if (position == TOOLBAR_ITEM_CURTAIN) {
			if (iPosition != TOOLBAR_ITEM_CURTAIN) {
				setContainerView(CURTAIN_CONTROL_ACTIVITY,
						CurtainControlActivity.class);
				iPosition = TOOLBAR_ITEM_CURTAIN;
			}

		} else if (position == TOOLBAR_ITEM_CLIMATE) {
			if (iPosition != TOOLBAR_ITEM_CLIMATE) {
				setContainerView(CLIMATE_LOGIN_ACTIVITY,
						ClimateControlActivity.class);
				iPosition = TOOLBAR_ITEM_CLIMATE;
			}
		} else if (position == TOOLBAR_ITEM_CAMERA) {
			setContainerView(CAMERA_CONTROL_ACTIVITY,
					CameraControlActivity.class);
			iPosition = TOOLBAR_ITEM_CAMERA;
		} else if (position == TOOLBAR_ITEM_LOCK) {
			if (iPosition != TOOLBAR_ITEM_LOCK) {
				setContainerView(LOCK_CONTROL_ACTIVITY,
						LockControlActivity.class);
				iPosition = TOOLBAR_ITEM_LOCK;
			}
		} else if (position == TOOLBAR_ITEM_SENSORS) {
			if (iPosition != TOOLBAR_ITEM_SENSORS) {
				setContainerView(SENSORS_CONTROL_ACTIVITY,
						SensorsControlActivity.class);
				iPosition = TOOLBAR_ITEM_SENSORS;
			}
		} else if (position == TOOLBAR_ITEM_SETTING) {
			if (iPosition != TOOLBAR_ITEM_SETTING) {
				setContainerView(SYSTEM_SETTING_ACTIVITY,
						SystemSettingActivity.class);
				iPosition = TOOLBAR_ITEM_SETTING;
			}
		}

	}

	@Override
	public void onClick(View v) {

		Integer position = (Integer) v.getTag();

		switch (v.getId()) {

		case R.id.btn_default1_sensor_setting:
			senceSetting(position);
			break;
		case R.id.btn_default2_sensor_setting:
			senceSetting(position);
			break;
		case R.id.btn_previous_room:
			currentRoomPositionInList = currentRoomPositionInList - 1;
			listenBtnState();
			Room preRoom = roomOfArray.get(currentRoomPositionInList);
			Global.getInstance().setRoomID(preRoom.id);
			Global.getInstance().setSerialNumber(preRoom.serialNumber);
			PollLoop.getInstance().refreshAll();
			txt_currentRoom_name.setText(preRoom.name);

			break;
		case R.id.btn_next_room:
			currentRoomPositionInList = currentRoomPositionInList + 1;
			listenBtnState();
			Room nextRoom = roomOfArray.get(currentRoomPositionInList);
			Global.getInstance().setRoomID(nextRoom.id);
			Global.getInstance().setSerialNumber(nextRoom.serialNumber);
			PollLoop.getInstance().refreshAll();
			txt_currentRoom_name.setText(nextRoom.name);

			break;
		case R.id.txt_current_room:

			loadRoomView();
			popOfAllRoom.showAsDropDown(txt_currentRoom_name, 0, 0);

			break;
		case R.id.refresh:
			if (Global.getInstance().getIsRuningWeather() == false
					&& current_city != null)
				new GetWeatherInfo(MainActivityGroup.this, current_city,
						mProgressBar, iv_weather, txt_weather_info).execute();
			if (!txt_weather_info.getText().toString().equals(""))
				Global.getInstance().showTextToast(MainActivityGroup.this,
						txt_weather_info.getText().toString());
			break;
		default:
			break;
		}
	}

	private void listenBtnState() {
		if (currentRoomPositionInList == 0) {
			btn_previous_room.setVisibility(View.INVISIBLE);
		} else {
			btn_previous_room.setVisibility(View.VISIBLE);
		}
		if (currentRoomPositionInList == roomOfArray.size() - 1) {
			btn_next_room.setVisibility(View.INVISIBLE);
		} else {
			btn_next_room.setVisibility(View.VISIBLE);
		}
	}

	private void senceSetting(int position) {

		Cursor cursor = MainDBAdapter.getInstance().getShortCutKeyScene(
				Settings.getInstance().getCurrentUsername(), position);// 查询选中的条目
		while (cursor.moveToNext()) {
			String senceID = cursor.getString(cursor.getColumnIndex("MID"));
			String senceSerialNumber = cursor.getString(cursor
					.getColumnIndex("MVeraSerial"));

			OpenSenceAsyncTask sensotThread = new OpenSenceAsyncTask(
					senceSerialNumber, senceID);
			addTask(sensotThread);
		}
		cursor.close();
	}

	class OpenSenceAsyncTask extends AsyncTask<Void, Void, String> {

		private int serialNumber;
		private int id;

		public OpenSenceAsyncTask(String serialNumber, String id) {

			this.serialNumber = Integer.parseInt(serialNumber);
			this.id = Integer.parseInt(id);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			isRunning = true;
		}

		protected String doInBackground(Void... params) {

			Scene mScene = Scene.findScenesByID(PollLoop.getInstance()
					.getScenes(), serialNumber, id);
			if (mScene != null)
				return WebData
						.getInstance()
						.sendServiceActionWithResponse(
								PollLoop.getInstance()
										.getEngineForSerialNumber(serialNumber),
								"action",
								URLEncoder
										.encode("urn:micasaverde-com:serviceId:HomeAutomationGateway1"),
								"RunScene", "SceneNum=" + id);
			else
				return null;

		}

		@Override
		protected void onPostExecute(String result) {

			if (result != null && result.startsWith("ERROR")) {
				Toast.makeText(MainActivityGroup.this, result.substring(6),
						Toast.LENGTH_SHORT).show();
			}

			isRunning = false;

			if (!arrayOfOpenSence.isEmpty()) {

				OpenSenceAsyncTask mOpenSenceAsyncTask = arrayOfOpenSence
						.get(0);
				arrayOfOpenSence.remove(0);

				mOpenSenceAsyncTask.execute();
			}

		}
	}

	private void addTask(OpenSenceAsyncTask task) {

		if (arrayOfOpenSence.isEmpty() && !isRunning) {
			task.execute();
			TLog.d("ClimateControlThread execute");
		} else {
			arrayOfOpenSence.add(task);
		}
	}

	private List<Scene> getSence() {

		Map<String, Scene> allScenes = PollLoop.getInstance().getScenes();
		List<Scene> scenes = Scene.findScenesByRoom(allScenes, -1, -1);
		return scenes;
	}

	class GetFetchDataAsyncTask extends
			AsyncTask<Void, Void, Map<Integer, Engine>> {

		Dialog dialog = null;

		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(MainActivityGroup.this, "",
					res.getString(R.string.fetching_vera_data), true, true);
			// dialog.setOnCancelListener(new OnCancelListener() {
			// public void onCancel(DialogInterface dialog) {
			// cancel(true);
			// }
			// });

			dialog.show();
		}

		protected Map<Integer, Engine> doInBackground(Void... params) {
			return WebData.getInstance().fetchEngines(MainActivityGroup.this,
					Settings.getInstance().getHwKey(),
					Settings.getInstance().getPkAccessory(),
					Settings.getInstance().getCurrentUsername());
		}

		@Override
		protected void onPostExecute(Map<Integer, Engine> result) {

			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}

			if (result == null) {
				Toast.makeText(MainActivityGroup.this,
						res.getString(R.string.cannot_reach_the_vera_network),
						Toast.LENGTH_LONG).show();
				return;
			}

			if (result.size() == 0) {
				Toast.makeText(MainActivityGroup.this,
						res.getString(R.string.cannot_reach_the_vera_count),
						Toast.LENGTH_LONG).show();
				return;
			}

			Global.getInstance().setEngines(result);

			ArrayList<String> arrayOfVeras = MainDBAdapter.getInstance()
					.getAllVeraSerialForUser(
							Settings.getInstance().getCurrentUsername());

			ArrayList<Engine> arrayOfSelectVera = new ArrayList<Engine>();

			for (String str : arrayOfVeras) {

				Engine engine = result.get(Integer.parseInt(str));
				if (engine != null)
					arrayOfSelectVera.add(engine);
			}

			PollLoop.getInstance().setArrayOfSelectVera(arrayOfSelectVera);
			PollLoop.getInstance().startPollLoop();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		PollLoop.getInstance().stopPollLoop();
		Global.getInstance().setRoomID(-1);
		Global.getInstance().setSerialNumber(-1);
		// Global.getInstance().getEngines().clear();
	}

	@Override
	public boolean onLongClick(View view) {

		Integer position = (Integer) view.getTag();
		loadSceneView(position);

		popOfAllScene.showAsDropDown(view, 0, 0);
		return true;
	}

	private void loadSceneView(int position) {

		arrayOfScence.clear();
		arrayOfScence.addAll(getSence());

		arrayOfSelectedData.clear();
		arrayOfSelectedData.addAll(getSelectSenceData(position));

		LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) gv_scene_list
				.getLayoutParams();

		int count = arrayOfScence.size();
		lp.width = (int) (count * 70 * displayMetrics)
				+ (int) (((count > 0 ? count : 1) - 1) * 10 * displayMetrics);
		gv_scene_list.setNumColumns(arrayOfScence.size());
		mScenePopGridViewAdapter.setFlag(position);

		mScenePopGridViewAdapter.notifyDataSetChanged();

	}

	public ArrayList<String> getSelectSenceData(int position) {

		ArrayList<String> arrayOfData = new ArrayList<String>();

		Cursor curosrShortCutKey = MainDBAdapter.getInstance()
				.getShortCutKeyScene(
						Settings.getInstance().getCurrentUsername(), position);
		if (curosrShortCutKey != null) {
			while (curosrShortCutKey.moveToNext()) {

				String serialNumber = curosrShortCutKey
						.getString(curosrShortCutKey
								.getColumnIndex("MVeraSerial"));
				String id = curosrShortCutKey.getString(curosrShortCutKey
						.getColumnIndex("MID"));
				arrayOfData.add(serialNumber + id);
			}
		}
		curosrShortCutKey.close();

		return arrayOfData;

	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			this.getLocalActivityManager().getCurrentActivity().onBackPressed();
			return false;
		} else {
			return super.onKeyUp(keyCode, event);
		}

	}
}